package com.htgd.gardenexpo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.htgd.gardenexpo.dao.GeConTheaterPlanMovieMapper;
import com.htgd.gardenexpo.entity.CommonResult;
import com.htgd.gardenexpo.entity.GeConTheaterPlanMovie;
import com.htgd.gardenexpo.entity.WxUserTheaterTicket;
import com.htgd.gardenexpo.dao.WxUserTheaterTicketMapper;
import com.htgd.gardenexpo.service.IWxUserTheaterTicketService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * <p>
 * 微信用户剧场投票详情 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-10-22
 */
@Service
public class WxUserTheaterTicketServiceImpl extends ServiceImpl<WxUserTheaterTicketMapper, WxUserTheaterTicket> implements IWxUserTheaterTicketService {

    @Autowired
    private WxUserTheaterTicketMapper wxUserTheaterTicketMapper;

    @Autowired
    private GeConTheaterPlanMovieMapper geConTheaterPlanMovieMapper;

    @Autowired
    private IWxUserTheaterTicketService wxUserTheaterTicketService;

    @Transactional
    @Override
    public CommonResult add(String openId, WxUserTheaterTicket wxUserTheaterTicket) {
        //判断是否投过
        boolean exists = lambdaQuery().eq(WxUserTheaterTicket::getOpenId, openId)
                .eq(WxUserTheaterTicket::getPlanId, wxUserTheaterTicket.getPlanId()).exists();
        if(exists){
            return CommonResult.error("你已经投过票了，不能重复投票");
        }
        //数据插入
        wxUserTheaterTicket.setOpenId(openId);
        wxUserTheaterTicketMapper.insert(wxUserTheaterTicket);
        //更新票数
        GeConTheaterPlanMovie geConTheaterPlanMovie = geConTheaterPlanMovieMapper.selectOne(new LambdaQueryWrapper<GeConTheaterPlanMovie>()
            .eq(GeConTheaterPlanMovie::getPlanId,wxUserTheaterTicket.getPlanId())
            .eq(GeConTheaterPlanMovie::getMovieId,wxUserTheaterTicket.getMovieId())
            .last("limit 1"));
        if(Objects.nonNull(geConTheaterPlanMovie)){
            geConTheaterPlanMovie.setTickets(geConTheaterPlanMovie.getTickets()+1);
            geConTheaterPlanMovieMapper.updateById(geConTheaterPlanMovie);
        }else{
            GeConTheaterPlanMovie geConTheaterPlanMovie1 = new GeConTheaterPlanMovie();
            geConTheaterPlanMovie1.setMovieId(wxUserTheaterTicket.getMovieId());
            geConTheaterPlanMovie1.setPlanId(wxUserTheaterTicket.getPlanId());
            geConTheaterPlanMovie1.setTickets(1);
            geConTheaterPlanMovieMapper.insert(geConTheaterPlanMovie1);
        }
        return CommonResult.success("投票成功");
    }

    @Override
    public WxUserTheaterTicket isVote(String openId, String movieId, String planId) {
        return wxUserTheaterTicketMapper.isVote(openId, movieId, planId);
    }

}
